import { defineStore } from "pinia";
import { getOrderList } from '@/api/order.js';

// 定义名为 'orderData' 的 Pinia store
export const useOrderDatastore = defineStore("orderData", {
  // state 定义存储状态
  state: () => ({
    orderDatas: [], // 存储订单数据的数组
    searchQuery: '', // 搜索查询字符串
  }),
  // actions 定义可执行的操作
  actions: {
    // 获取订单数据的操作
    async getOrderData() {
      try {
        const res = await getOrderList();
        if (res.data.code === 200) {
          this.orderDatas = res.data.list;
        }
      } catch (error) {
        console.error("Error", error);
      }
    },
    // 搜索订单
    setSearchQuery(query) {
      this.searchQuery = query;
    }
  },
  // 定义 store 的 getters
  getters: {
    // 获取所有订单
    orderItems: (state) => state.orderDatas,
    // 根据搜索查询获取过滤后的订单
    filteredOrders: (state) => {
      if (!state.searchQuery) {
        return state.orderDatas;
      }
      return state.orderDatas.filter(order =>
        order.orderId.includes(state.searchQuery) ||
        order.name.includes(state.searchQuery) ||
        order.userName.includes(state.searchQuery)
      );
    }
  },
  // persist 配置持久化
  persist: {
    enabled: true,
    strategies: [
      {
        key: "orderData",
        storage: localStorage,
      },
    ],
  },
});
